<template>
  <div>
    <h1>防抖与节流</h1>
    <div>
      <el-input
        v-model="inputValue"
        style="width: 240px"
        placeholder="请输入关键词"
      />
      <el-button @click="btFn">搜索</el-button>
    </div>
    <div v-if="dreamValue.list.length == 0" class="msgSty">
      {{ dreamValue.msg }}
    </div>
    <div v-else>
      <div v-for="(item, index) in dreamValue.list" :key="index">
        <div><span class="fenlei">分类：</span> {{ item.slx }}</div>
        <div><span class="fenlei">梦解：</span>{{ item.result }}</div>
      </div>
    </div>
  </div>
</template>

<!-- <script setup lang="ts"> -->
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { gushiApi } from '../../api/yunxiApi'
let showTop = () => {
  var scrollTop = document.body.scrollTop || document.documentElement.scrollTop
  console.log('滚动条位置：' + scrollTop)
}

// 防抖
function debounce (fn, delay) {
  let timer = null //借助闭包
  return function () {
    if (timer) {
      clearTimeout(timer)
    }
    console.log('呜呜呜呜')
    timer = setTimeout(fn, delay) // 简化写法
  }
}

// 节流
function throttle (fn, delay) {
  let valid = true
  console.log('aaaa', valid)

  return function () {
    console.log('000', valid)
    if (!valid) {
      console.log('111', valid)
      return false
    }

    valid = false
    console.log('222', valid)

    setTimeout(() => {
      fn()
      valid = true
      console.log('333', valid)
    }, delay)
  }
}

const inputValue = ref('')
const dreamValue = reactive({
  list: [],
  msg: ''
})

const resApi = async () => {
  let prams = reactive({
    key: '7d06a110e9e20a684e02934549db1d3d',
    text: inputValue.value,
    api: '94'
  })
  let res = await gushiApi(prams)
  console.log('res', res)

  if (res.data.code == 111) {
    dreamValue.msg = res.data.msg
  }
  dreamValue.list = res.data.data
}

// window.onscroll = debounce(showTop, 1000)
window.onscroll = throttle(showTop, 10000)
function btFn () {
  console.log('xxxxxx', inputValue.value)
  resApi()
}
</script>

<style scoped>
.fenlei {
  color: aqua;
}
.msgSty {
  size: 22px;
  color: coral;
}
</style>
